<?php

namespace app\mall\logic;

use app\data\controller\api\Data;
use app\data\model\DataUser;
use app\mall_back\model\GoodsLuckyDrawModel;
use app\mall_back\model\TescoRecordModel;
use think\admin\model\SystemBase;
use think\Exception;
use think\facade\Db;
use think\helper\Arr;
use think\model\Collection;

class indexLogic
{

    /**
     * 商品分类
     *
     * @param int $pid
     */
    public function goods_classify(int $pid)
    {
        $where = [
            ['pid', '=', $pid],
            ['status', '=', 1],
            ['deleted', '=', 0],
        ];
        return Db::table('shop_goods_cate')
            ->where($where)
            ->order(['sort' => 'desc', 'create_at' => 'desc'])
            ->field('id ,name ,cover ,remark')
            ->select();
    }

    /**
     * 商品列表
     *
     * @param int    $one_cate_id 一级分类id
     * @param int    $two_cate_id 二级分类id
     * @param int    $is_hot      是否热门
     * @param int    $is_new      即将满员
     * @param string $order       排序字段
     * @param string $sort        asc正序 desc倒叙
     * @param int    $page        页数
     * @param int    $limit       每页数量
     *
     * @return array
     */
    public function goods_list(int $one_cate_id, int $two_cate_id, int $is_hot, int $is_new, string $order, string $sort, int $page, int $limit): array
    {
        $where = [
            ['d.status', '=', GoodsLuckyDrawModel::STATE_STARTING]
        ];
        if (!empty($one_cate_id)) {
            $where[] = ['g.one_cate_id', '=', $one_cate_id];
        }
        if (!empty($two_cate_id)) {
            $where[] = ['g.two_cate_id', '=', $two_cate_id];
        }
        if (!empty($is_hot)) {
            $where[] = ['d.is_hot', '=', $is_hot];
        }

        if ($is_new) {
            $order = 'd.create_time';
            $sort  = 'DESC';
        }

        if (!empty($order)) {
            if ($order == 'quick') {
                $order = 'd.residue_number * d.unit_price';
            }
            if ($order == 'price') {
                $order = 'd.unit_price';
            }
        } else {
            $order = 'd.create_time';
            $sort  = 'DESC';
        }

        $fields = [
            "d.id", "goods_id", "people_number", "participants_number", "residue_number", "unit_price",
            "sequence_no", "sequence_total", "sequence_current", "draw_delay", "d.create_time"
        ];

        $list = Db::table('one_goods_lucky_draw')
            ->alias('d')
            ->field($fields)
            ->view('one_goods g', 'goods_name, cover', 'd.goods_id = g.id')
            ->where($where)
            ->orderRaw("${order} ${sort}")
            ->paginate($limit);
        $list = $list->items();
        if ($list) {
            foreach ($list as $key => $value) {
                $participants_percent = bcMath($value['participants_number'], $value['people_number'], '/');

                if ($participants_percent > 1) {
                    $participants_percent = 1;
                }
                $list[$key]['participants_percent'] = $participants_percent;
            }
        }
        return $list;
    }

    public function drawing_list($page, $limit)
    {
        $where = [
            ['d.status', 'IN', [GoodsLuckyDrawModel::STATE_DRAWING, GoodsLuckyDrawModel::STATE_FINISHED]]
        ];

        $fields = [
            "d.id", "goods_id","sequence_no","sequence_current", "win_time",
            "people_number", "draw_delay", "d.status", "d.create_time",
            "d.winning_user_id", "award_number"
        ];

        $list = Db::table('one_goods_lucky_draw d')
            ->field($fields)
            ->view('one_goods g', 'goods_name, cover', 'd.goods_id = g.id')
            ->where($where)
            ->orderRaw("d.win_time DESC, d.status ASC, id DESC")
            ->paginate($limit);

        $list = $list->items();
        foreach ($list as $i => $item) {
            $list[$i]['status_text'] = GoodsLuckyDrawModel::getStatusText($item['status']);
            $list[$i]['bought_number'] = TescoRecordModel::where('goods_lucky_draw_id', $item['id'])->count();
            if ($item['winning_user_id'] > 0) {
                $user                     = DataUser::where('id', '=', $item['winning_user_id'])->find();
                $list[$i]['winning_user'] = [
                    'id' => $user->id, 'nickname' => $user->nickname, 'headimg' => $user->headimg, 'phone' => $user->phone
                ];
            } else {
                $list[$i]['winning_user'] = new \ArrayObject();
            }
        }

        return $list;
    }

    public function booking_list($uid, $page, $limit) {
        $where = [ ['d.status', 'IN', [GoodsLuckyDrawModel::STATE_PENDING]] ];
        $fields = ["d.id", "d.goods_id", "unit_price", "people_number", "participants_number",
                   "sequence_no", "sequence_current", "sequence_total"];

        $list = Db::table('one_goods_lucky_draw')
            ->alias('d')
            ->field($fields)
            ->leftJoin('one_goods g', 'd.goods_id = g.id')
            ->field('g.id, goods_name, cover')
            ->leftJoin('one_tesco_record tr', 'tr.goods_lucky_draw_id = d.id and tr.u_id = ' . $uid)
            ->field('GROUP_CONCAT(lucky_number) AS lucky_numbers, tr.create_time')
            ->where($where)
            ->group('d.id')
            ->having('GROUP_CONCAT(lucky_number) > 0')
            ->orderRaw("d.id DESC")
            ->paginate($limit);

        return $list;
    }

    public function thugs_list($page, $limit)
    {
        $userInfos = TescoRecordModel::alias('r')
            ->fieldRaw('r.u_id AS uid, u.nickname, u.headimg, COUNT(DISTINCT r.id) AS buy_num, COUNT(DISTINCT r.goods_lucky_draw_id) AS draw_num')
            ->leftJoin('data_user u', 'r.u_id = u.id')
            ->group('u_id')
            ->select();

        return $userInfos;
    }

    /**
     * 商品详情
     *
     * @param int $id  抽奖商品信息id，one_goods_lucky_draw表id
     * @param int $uid 用户id
     *
     * @return array
     */
    public function goods_details(int $id, int $uid): array
    {
        $fields     = [
            "d.id", "goods_id", "unit_price", "people_number", "participants_number", "residue_number",
            "sequence_no", "sequence_total", "sequence_current", "draw_delay",
            'd.status', "win_time", "d.create_time"
        ];
        $lucky_draw = Db::table('one_goods_lucky_draw d')
            ->where('id', '=', $id)
            ->field($fields)
            ->find();
        if (empty($lucky_draw)) return [];
        $goods_info = Db::table('one_goods')
            ->where('id', '=', $lucky_draw['goods_id'])
            ->field('goods_name,slider,remark,content,goods_price')
            ->find();

        $my_join_number   = 0;
        $my_join_list     = [];
        $my_join_str      = '';
        $TescoRecordModel = new TescoRecordModel();
        if ($uid) {
            //我购买的相关信息
            $join_record    = $TescoRecordModel->where(['u_id' => $uid, 'goods_lucky_draw_id' => $id])->column('lucky_number');
            $my_join_list   = $join_record;
            $my_join_number = count($join_record);
            foreach ($join_record as $key => $value) {
                if ($key < 3) {
                    $my_join_str .= "幸运号码" . $value . "、";
                } else {
                    break;
                }
            }
        }
        //本期参加
        $join_record_user = $TescoRecordModel->where(['goods_lucky_draw_id' => $id])->group('u_id')->column('u_id,create_time');
        $join_record_list = [];
        if ($join_record_user) {
            foreach ($join_record_user as $key => $value) {
                $user      = DataUser::mk()->where(['id' => $value['u_id']])->field('id,nickname,headimg')->find();
                $count     = $TescoRecordModel->where('goods_lucky_draw_id', $id)->where(['u_id' => $value['u_id']])->count();
                $join_user = [
                    'id'        => $user['id'],
                    'nickname'  => $user['nickname'],
                    'headimg'   => $user['headimg'],
                    'join_num'  => $count,
                    'join_time' => $value['create_time'],
                ];
                array_push($join_record_list, $join_user);
            }
        }
        //往期获奖名单
        $reward_record = $TescoRecordModel->alias('t')
            ->join('data_user u', 'u.id=t.u_id')
            ->where(['t.goods_id' => $lucky_draw['goods_id'], 't.is_win' => 1])
            ->field('u.id as user_id,u.headimg,u.nickname,t.lucky_number,t.is_win,t.goods_id,t.u_id')
            ->select();
        if ($reward_record) {
            foreach ($reward_record as $key => $value) {
                $reward_record[$key]['win_time'] = $lucky_draw['win_time'];
            }
        }
//        var_dump($reward_record);
//        die;
        //统计信息
        $surplus_number       = $lucky_draw['people_number'] - $lucky_draw['participants_number'];
        $participants_percent = bcMath($lucky_draw['participants_number'], $lucky_draw['people_number'], '/');
        return [
            'id'                   => $id,
            'goods_id'             => $lucky_draw['goods_id'],//商品id
            'people_number'        => $lucky_draw['people_number'],//参与总人数(所需人数)
            'participants_number'  => $lucky_draw['participants_number'],//参与人数
            'surplus_number'       => $surplus_number,//剩余人数
            'participants_percent' => $participants_percent,//参与百分比
            'my_join_number'       => $my_join_number,//我参与的人次
            'my_join_str'          => $my_join_str,//我参与的幸运号码
            'my_join_list'         => $my_join_list,//我的购买
            'join_record_list'     => $join_record_list,//本期参加
            'reward_record'        => $reward_record,//往期获奖名单
            'unit_price'           => $lucky_draw['unit_price'],//单价
            'goods_price'          => $goods_info['goods_price'],//商品价格
            'goods_name'           => $goods_info['goods_name'],//商品名称
            'slider'               => explode('|', $goods_info['slider']),//轮播图
            'sequence_no'          => $lucky_draw['sequence_no'],
            'sequence_total'       => $lucky_draw['sequence_total'],
            'sequence_current'     => $lucky_draw['sequence_current'],
            'status'               => $lucky_draw['status'],
            'status_text'          => GoodsLuckyDrawModel::getStatusText($lucky_draw['status']),
            'remark'               => $goods_info['remark'],//描述
            'content'              => $goods_info['content']//详情
        ];
    }

    public function lottery_board($id)
    {
        $firstJoin = json_decode('{}');
        $uid       = TescoRecordModel::where('goods_lucky_draw_id', $id)
            ->order('create_time', 'ASC')
            ->value('u_id');
        if ($uid > 0) {
            $firstJoin = DataUser::field('id, nickname, headimg')->find($uid)->toArray();
        }

        $mostBuy  = json_decode('{}');
        $buyCount = $mostBuyUid = 0;
        $result   = TescoRecordModel::where('goods_lucky_draw_id', $id)
            ->group('u_id')
            ->field('u_id, COUNT(id) AS num')
            ->having('COUNT(id) > 0')
            ->orderRaw('COUNT(id) DESC')
            ->find();

        if ($result) {
            ['u_id' => $mostBuyUid, 'num' => $buyCount] = $result->toArray();
            $mostBuy              = DataUser::field('id, nickname, headimg')->find($uid)->toArray();
            $mostBuy['buy_count'] = $buyCount;
        }

        $lastBuy = json_decode('{}');
        $lastUid = TescoRecordModel::alias('t')
            ->where('goods_lucky_draw_id', $id)
            ->leftJoin('one_goods_lucky_draw d', 'd.id = t.goods_lucky_draw_id')
            ->where('d.residue_number', '=', 0)
            ->order('t.create_time', 'DESC')
            ->find();
        $lastu = DataUser::field('id, nickname, headimg')->find($lastUid);
        if ($lastUid && $lastUid['u_id'] > 0 && $lastu) {
            $lastBuy = $lastu->toArray();
        }

        return ['first_join' => $firstJoin, 'most_buy' => $mostBuy, 'last_join' => $lastBuy];
    }

    public function lottery_chart($id)
    {
        /** @var GoodsLuckyDrawModel $drawInfo */
        $drawInfo = GoodsLuckyDrawModel::find($id);
        if ($drawInfo->sequence_total <= 1) {
            return [];
        }

        $response = cache("lottery_chart-{$id}");
        if (!$response) {
            $drawInfos = GoodsLuckyDrawModel::alias('d')
                ->field('d.id,goods_id,sequence_no,sequence_total,sequence_current,people_number,award_number')
                ->field('u.id AS uid, u.nickname, u.headimg')
                ->leftJoin('data_user u', 'u.id = d.winning_user_id')
                ->where('d.sequence_no', $drawInfo->sequence_no)
                ->where('d.status', '=', GoodsLuckyDrawModel::STATE_FINISHED)
                ->select();

            $drawIds = array_column($drawInfos->toArray(), 'id');

            $winRecords = TescoRecordModel::where('goods_lucky_draw_id', 'IN', $drawIds)
                ->where('is_win', 1)
                ->column('id', 'goods_lucky_draw_id');

            $response = [];
            foreach ($drawInfos as $drawInfo) {
                $item = $drawInfo->toArray();
                Arr::forget($item, ["uid", "nickname", "headimg"]);

                $item['win_user']  = Arr::only($drawInfo->toArray(), ["uid", "nickname", "headimg"]);
                $item['bought']    = TescoRecordModel::where('u_id', $drawInfo->uid)
                    ->where('goods_lucky_draw_id', $drawInfo->id)
                    ->count();
                $item['seq_index'] = TescoRecordModel::where('goods_lucky_draw_id', $drawInfo->id)
                    ->where('id', '<=', $winRecords[$drawInfo->id])
                    ->count();
                $item['seq_part']  = ceil(bcdiv($item['seq_index'], $drawInfo->people_number / 5, 2));

                $response[] = $item;
            }
            cache("lottery_chart-{$id}", $response, ['expire' => 300]);
        }

        return $response;
    }

    public function promo_goods()
    {
        $results       = sysdata('promos');
        $default_promo = ['cover' => '', 'draw_id' => '0'];

        return [
            'left_module'   => [
                'title' => $results[0]['title'] ?? '',
                'promo' => isset($results[0]) ? ['cover' => $results[0]['img'], 'goods_lucky_draw_id' => $results[0]['draw_id']] : $default_promo
            ],
            'right_modules' => [
                [
                    'title' => $results[1]['title'] ?? '',
                    'promo' => isset($results[1]) ? ['cover' => $results[1]['img'], 'goods_lucky_draw_id' => $results[1]['draw_id']] : $default_promo
                ], [
                    'title' => $results[2]['title'] ?? '',
                    'promo' => isset($results[2]) ? ['cover' => $results[2]['img'], 'goods_lucky_draw_id' => $results[2]['draw_id']] : $default_promo
                ], [
                    'title' => $results[3]['title'] ?? '',
                    'promo' => isset($results[3]) ? ['cover' => $results[3]['img'], 'goods_lucky_draw_id' => $results[3]['draw_id']] : $default_promo
                ], [
                    'title' => $results[4]['title'] ?? '',
                    'promo' => isset($results[4]) ? ['cover' => $results[4]['img'], 'goods_lucky_draw_id' => $results[4]['draw_id']] : $default_promo
                ]
            ]
        ];
    }
}